package com.zbkj.front.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.zbkj.common.model.communityOrder.NoteTopic;
import com.zbkj.common.model.merchant.Merchant;
import com.zbkj.common.model.merchant.MerchantCategory;
import com.zbkj.common.model.page.PageDiy;
import com.zbkj.common.model.product.Product;
import com.zbkj.common.model.system.SystemConfig;
import com.zbkj.common.model.together.TogetherJob;
import com.zbkj.common.model.together.UserTogether;
import com.zbkj.common.model.user.User;
import com.zbkj.common.model.user.UserJob;
import com.zbkj.common.page.CommonPage;
import com.zbkj.common.request.PageParamRequest;
import com.zbkj.common.request.ProductFrontSearchRequest;
import com.zbkj.common.response.IndexInfoResponse;
import com.zbkj.common.response.ProductDetailResponse;
import com.zbkj.common.response.ProductFrontResponse;
import com.zbkj.common.result.CommonResult;
import com.zbkj.common.vo.ProCategoryCacheVo;
import com.zbkj.front.service.FrontProductService;
import com.zbkj.front.service.IndexService;
import com.zbkj.service.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@RestController
@RequestMapping("api/person/home")
@Api(tags = "人脉控制器") //配合swagger使用
public class HomeAndPersonController {


    @Autowired
    private UserService userService;

    @Autowired
    private MerchantService merchantService;

    @Autowired
    private ProductCategoryService productCategoryService;

    @Autowired
    private FrontProductService productService;

    @Autowired
    private MerchantCategoryService merchantCategoryService;

    @Autowired
    private NoteTopicService noteTopicService;

    @Autowired
    private PageDiyService pageDiyService;

    @Autowired
    private UserJobService userJobService;


    @ApiOperation(value = "分类人脉列表")
    @RequestMapping(value = "/getI", method = RequestMethod.GET)
    public CommonResult< List<MerchantCategory>> getMerchantCategory(String catIds) {

        LambdaQueryWrapper<MerchantCategory> categoryQ = Wrappers.lambdaQuery();
        if (catIds!=null && !catIds.equals("")){
            String[] items = catIds.split(",");
            List<Integer> appIdList = Stream.of(items).map(Integer::parseInt).collect(Collectors.toList());
            categoryQ.in(MerchantCategory::getId, appIdList);

//            categoryQ.apply(StrUtil.format(" find_in_set(id,'{}' )", catIds));
        }
        List<MerchantCategory> list = merchantCategoryService.list(categoryQ);
        for (MerchantCategory category:list){
            Integer id = category.getId();
            LambdaQueryWrapper<Merchant> lqw = Wrappers.lambdaQuery();

            lqw.in(Merchant::getCategoryId, id);
            lqw.isNotNull(Merchant::getUserId);
            List<Merchant> list1 = merchantService.list(lqw);
            List<Integer> collect = list1.stream().map(Merchant::getUserId).collect(Collectors.toList());


            String ids = StringUtils.join(collect.toArray(), ",");
            LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery();

            queryWrapper.in(User::getId, ids);
            List<User> userList = userService.list(queryWrapper);
            for (User user:userList){
                LambdaQueryWrapper<Merchant> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(Merchant::getUserId, user.getId());
                Merchant one = merchantService.getOne(queryWrapper1);
                if (one!=null) {
                    LambdaQueryWrapper<MerchantCategory> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.in(MerchantCategory::getId, one.getCategoryId());
                    List<String> collect1 = merchantCategoryService.list(lambdaQueryWrapper).stream().map(MerchantCategory::getName).collect(Collectors.toList());
                    String ids1 = StringUtils.join(collect1.toArray(), ",");
                    user.setCategory(ids1);
                }
            }
            category.setUserList(userList);
        }
        return CommonResult.success(list);
    }

    @ApiOperation(value = "分类人脉列表(只显示用户)")
    @RequestMapping(value = "/getU", method = RequestMethod.GET)
    public CommonResult< List<User>> getU(String catIds) {

        LambdaQueryWrapper<MerchantCategory> categoryQ = Wrappers.lambdaQuery();
        if (catIds!=null && !catIds.equals("")){
            String[] items = catIds.split(",");
            List<Integer> appIdList = Stream.of(items).map(Integer::parseInt).collect(Collectors.toList());
            categoryQ.in(MerchantCategory::getId, appIdList);

//            categoryQ.apply(StrUtil.format(" find_in_set(id,'{}' )", catIds));
        }

        List<User> userList = new ArrayList<>();
        List<MerchantCategory> list = merchantCategoryService.list(categoryQ);
        if (catIds!=null && !catIds.equals("")) {
            for (MerchantCategory category:list){
                Integer id = category.getId();
                LambdaQueryWrapper<Merchant> lqw = Wrappers.lambdaQuery();

                lqw.in(Merchant::getCategoryId, id);
                lqw.isNotNull(Merchant::getUserId);
                List<Merchant> list1 = merchantService.list(lqw);
                List<Integer> collect = list1.stream().map(Merchant::getUserId).collect(Collectors.toList());


                String ids = StringUtils.join(collect.toArray(), ",");
                LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery();

                queryWrapper.in(User::getId, ids);
                List<User> userListOne = userService.list(queryWrapper);
                if (userListOne.size()>0) {
                    userList.addAll(userListOne);
                }
                category.setUserList(userList);
            }
        }else{
            userList = userService.list();
        }

        for (User user:userList){
            LambdaQueryWrapper<Merchant> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Merchant::getUserId, user.getId());
            Merchant one = merchantService.getOne(queryWrapper);
            if (one!=null) {
                LambdaQueryWrapper<MerchantCategory> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.in(MerchantCategory::getId, one.getCategoryId());
                List<String> collect = merchantCategoryService.list(lambdaQueryWrapper).stream().map(MerchantCategory::getName).collect(Collectors.toList());
                String ids = StringUtils.join(collect.toArray(), ",");
                user.setCategory(ids);
            }
        }
        return CommonResult.success(userList);
    }

    @ApiOperation(value = "普通人脉列表")
    @RequestMapping(value = "/getR", method = RequestMethod.GET)
    public CommonResult<List<User>> getR(@ModelAttribute @Validated PageParamRequest pageParamRequest) {
        Page<Product> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<User> list = userService.list();
        for (User user:list){
            LambdaQueryWrapper<Merchant> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Merchant::getUserId, user.getId());
            Merchant one = merchantService.getOne(queryWrapper);
            if (one!=null) {
                LambdaQueryWrapper<MerchantCategory> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.in(MerchantCategory::getId, one.getCategoryId());
                List<String> collect = merchantCategoryService.list(lambdaQueryWrapper).stream().map(MerchantCategory::getName).collect(Collectors.toList());
                String ids = StringUtils.join(collect.toArray(), ",");
                user.setCategory(ids);
            }
        }
        return CommonResult.success(list);
    }



    @ApiOperation(value = "商品分页列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public CommonResult<CommonPage<ProductFrontResponse>> getList(@ModelAttribute @Validated ProductFrontSearchRequest request,
                                                                  @ModelAttribute @Validated PageParamRequest pageParamRequest
                                                                  ) {
        LambdaQueryWrapper<Merchant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Merchant::getUserId, request.getUserId());
        Merchant one = merchantService.getOne(queryWrapper);
        if (one!=null) {
            request.setMerId(one.getId().toString());
        }
        PageInfo<ProductFrontResponse> list = productService.getList(request, pageParamRequest);
        List<ProductFrontResponse> list1 = list.getList();
        for (ProductFrontResponse productFrontResponse:list1) {
            ProductDetailResponse normal = productService.getDetail(productFrontResponse.getId(), "normal");
            productFrontResponse.setProductDetailResponse(normal);
        }
        return CommonResult.success(CommonPage.restPage(list));
    }




    @ApiOperation(value = "分类缓存树")
    @RequestMapping(value = "/cache/tree", method = RequestMethod.GET)
    public CommonResult<List<ProCategoryCacheVo>> getMerchantCacheTree() {
        return CommonResult.success(productCategoryService.getMerchantCacheTree(null));
    }

    @ApiOperation(value = "查询修改模板2的值")
    @RequestMapping(value = "/getDiyInfoUpdate", method = RequestMethod.GET)
    public CommonResult<CommonPage<ProductFrontResponse>> getDiyInfoUpdate() {
        List<MerchantCategory> list = merchantCategoryService.list();
        for (MerchantCategory category:list){
            Integer id = category.getId();
            LambdaQueryWrapper<Merchant> lqw = Wrappers.lambdaQuery();

            lqw.in(Merchant::getCategoryId, id);
            lqw.isNotNull(Merchant::getUserId);
            List<Merchant> list1 = merchantService.list(lqw);
            List<Integer> collect = list1.stream().map(Merchant::getUserId).collect(Collectors.toList());


            String ids = StringUtils.join(collect.toArray(), ",");
            LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery();

            queryWrapper.in(User::getId, ids);
            List<User> userList = userService.list(queryWrapper);
            category.setUserList(userList);
        }
        PageDiy byId = pageDiyService.getById(2);
        HashMap map = new HashMap();
        map.put("data", list);
        Gson gson = new Gson();
        byId.setValue(gson.toJson(map));
        pageDiyService.saveOrUpdate(byId);
        return CommonResult.success();
    }


}
